import { Message } from "element-ui";

export const exportFileFn = function (
  exportFn,
  fileName,
  params,
  suffix = "xlsx"
) {
  return new Promise((resolve, reject) => {
    Message({
      type: "success",
      message: "正在导出，请稍后",
    });
    let xmlResquest = new XMLHttpRequest();
    xmlResquest.open("POST", exportFn, true);
    xmlResquest.setRequestHeader("Content-type", "application/json");
    xmlResquest.setRequestHeader(
      "Authorization",
      sessionStorage.getItem("token")
    );
    xmlResquest.responseType = "blob";

    xmlResquest.onload = function (oEvent) {
      // console.log(oEvent, xmlResquest)
      if (xmlResquest.status != 200) {
        Message({
          type: "error",
          message: "接口调用失败，请联系管理员",
        });
        reject(xmlResquest);
      } else {
        let content = xmlResquest.response;
        let blob = new Blob([content]);
        var reader = new FileReader();
        reader.onloadend = function () {
          var text = reader.result;
          try {
            let response = JSON.parse(text);
            Message({
              type: "error",
              message: response.msg,
            });
          } catch (error) {
            let elink = document.createElement("a");
            elink.download = `${fileName}.${suffix}`;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            resolve(xmlResquest);
          }
        };
        reader.readAsText(blob);
      }
    };
    // let params = this.axiosParams()
    xmlResquest.send(JSON.stringify(params));
  });
};
